package com.ja.rfid.exception;

/**
 * @author Kisen
 * @email liuqs@jaid.cn
 * @date 2022/11/8 18:05
 * @detail
 */

import com.ja.rfid.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常统一处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{}，异常类型：{}", e.getMessage(), e.getClass());

        // 获取所有异常
        List<String> errors = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(x -> x.getField() + x.getDefaultMessage())
                .collect(Collectors.toList());
        String message = String.join(",", errors);

        return R.error(-1, "数据校验异常").put("data", message);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e) {
        log.error("系统异常：{}", e);

        if (e instanceof RuntimeException) {
            RuntimeException ex = (RuntimeException) e;
            String message = ex.getMessage();
            return R.error(-1, message);

        } else {
            return R.error(-1, "系统异常");
        }
    }

}
